#include "Dwarf.Unmanaged.Mpi.h"

//Pointers to the factory functions.
static DLLParseArguments pDLLParseArguments;
static DLLUsage pDLLUsage;
static DLLStart pDLLStart;
static DLLStop pDLLStop;

//Pointers to dll.
static HINSTANCE hInstDll;

// Constructor that init strings.
Settings :: Settings()
{
    inputFile = new char[BUFFER_SIZE];
    resultFile = new char[BUFFER_SIZE];
	profileFile = new char[BUFFER_SIZE];

    inputFile[0] = resultFile[0] = profileFile[0] ='\0';
}

// Constructor that dispose strings.
Settings :: ~Settings()
{
    delete inputFile;
    delete resultFile;
	delete profileFile;
}

//fix: use fscanf_s
// Get one line from stream.
static void getNextLine(char* str, FILE* file) 
{
	short count = 0;
	char ch = ' ';    

    while (!feof(file) && (ch == ' ' || ch == '\n' || ch == '\r')) 
    {
        ch = getc(file);
	}

    str[count] = ch;
	while (!feof(file) && ch != '\r' && ch != '\n' && ch != ' ' && count < (BUFFER_SIZE-1)) 
    {
		str[++count] = (ch = getc(file));
	}
	
	str[count] = '\0';
}

// Parse input file into solver's structures.
int Settings::parseConfigFile(Solver* dlasolver) 
{
    FILE *file;

    // Open the file to read from.
    if( fopen_s(&file, inputFile, "rb")) 
    {
        printf("Can't open configfile!\r\n");
        (pDLLUsage)();

        return -1;
    }

// 	fix: using fscanf_s
    char *str = new char[BUFFER_SIZE];
//   Get size of matrices.
    getNextLine(str, file);
    dlasolver->msize = atoi(str);

//	fscanf_s(file, "%d\n", &dlasolver->msize);

    int i,j;

    //Init matrices.
    dlasolver->lgrid = new double*[dlasolver->msize];
    dlasolver->rgrid = new double*[dlasolver->msize];
    dlasolver->result = new double*[dlasolver->msize];
    for (j = 0; j < dlasolver->msize; j ++)
    {
        dlasolver->lgrid[j] = new double[dlasolver->msize];
        dlasolver->rgrid[j] = new double[dlasolver->msize];
        dlasolver->result[j] = new double[dlasolver->msize];
    }

    //Get left matrix.
    i = j = 0;
    while(!feof(file) && j < dlasolver->msize)
    {
		//fix: use fscanf_s
        getNextLine(str, file);
        dlasolver->lgrid[j][i] = atof(str);
		
//		fscanf_s(file, "%g\n", &dlasolver->lgrid[j][i]);

        i ++;

        if (i >= dlasolver->msize) 
        {
            i = 0;
            j ++;
        }
    }  

    //Get right matrix.
    i = j = 0;
    while(!feof(file) && j < dlasolver->msize)
    {
        //fix: use fscanf_s
        getNextLine(str, file);
        dlasolver->rgrid[j][i] = atof(str);
		
//		fscanf_s(file, "%g\n", &dlasolver->rgrid[j][i]);

        i ++;

        if (i >= dlasolver->msize) 
        {
            i = 0;
            j ++;
        }
    }

	//fix: using fscanf_s
    delete str;

    //Dispose input file.
    fclose(file);

    return 0;
}

// Init variables, parse cli params and input file.
int Settings::init(int argc, char** argv, Solver *dlasolver) 
{
    
    // Load the dll into the address space
 	//fix: C4706
	//if (!(hInstDll = LoadLibraryA("CliTools"))) 
    //{
	hInstDll = LoadLibraryA("CliTools");
	if(!hInstDll)
	{
       printf("Error while loading CliTools.dll.");
        return -1;
    }

    // Retrieve a pointer to the factory function
    pDLLParseArguments = 
        (DLLParseArguments) GetProcAddress(hInstDll, "parseArguments");

    pDLLUsage =
        (DLLUsage) GetProcAddress(hInstDll, "usage");

    pDLLStart = 
        (DLLStart) GetProcAddress(hInstDll, "start");

    pDLLStop = 
        (DLLStop) GetProcAddress(hInstDll, "stop");

    //Parse cli params.
    if ((pDLLParseArguments)(argc, argv, &inputFile, &profileFile,  &resultFile)) 
    {
        FreeLibrary(hInstDll); 
        return -1;
    }
    
    //Parse input file.
    if (parseConfigFile(dlasolver)) 
    {
        FreeLibrary(hInstDll); 
        return -1;
    }

    //Write settings if it's needed.
    writeSettings(dlasolver);	
    return 0;
}

// Start the time count.
void Settings::start() 
{
    (pDLLStart)();
}

// Problem results output.
void Settings::finish(Solver *dlasolver)
{
    double time;
    (pDLLStop)(&time);

    //Release dll.
    FreeLibrary(hInstDll);//*/

    printf("\r\n");
    printf("Clock time (sec): %.8f \r\n", time);  

        FILE* outputResult = 0;
        FILE* outputProfile = 0;

   if( fopen_s(&outputProfile, profileFile , "wb")) 
    {
        printf("Can't create profile file!\r\n");            
		fclose(outputProfile);
        return;
    }

    if( fopen_s(&outputResult, resultFile , "wb")) 
    {
        printf("Can't create result file!\r\n");   
        fclose(outputResult);
        return;
    }

        fprintf(outputProfile, "#Dwarfname:%s\r\n",DWARF_NAME);

        char tmpbuf[BUFFER_SIZE];
        _tzset();
        
        _strdate_s( tmpbuf, BUFFER_SIZE );
        fprintf(outputProfile, "#Time: %s ",tmpbuf);

        _strtime_s( tmpbuf, BUFFER_SIZE );
        fprintf(outputProfile, "%s \r\n",tmpbuf);

        fprintf(outputProfile, "#Dimensions: 2\r\n");
        fprintf(outputProfile, "#Matrix Size: %i\r\n", dlasolver->msize);
        fprintf(outputProfile, "#Result time (sec): %.8f\r\n", time);  
        fprintf(outputResult,"#Result domain:\r\n");
        for (int i = 0; i < dlasolver->msize; i ++) 
        {
            for (int j = 0; j < dlasolver->msize; j ++) 
            {                
                fprintf(outputResult,"%0.8f ", dlasolver->result[i][j]);
	        }
            fprintf(outputResult,"\r\n");
        }

        fprintf(outputProfile, "#eof");//*/

        fclose(outputProfile);
        fclose(outputResult);
	
}

// Write settings.
void Settings::writeSettings(Solver *dlasolver)
{
    // Write general settings.
    printf("Kernel settings summary : \r\n");
	printf("Dwarf name              : %s \r\n", DWARF_NAME);
    printf("Matrix size             : %d \r\n", dlasolver->msize);
	printf("Input file              : %s \r\n", inputFile);
	printf("Profile file            : %s \r\n", profileFile);    
	printf("Result file             : %s \r\n", resultFile);    
    printf("\r\n"); 

}